﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace ImmovablesManager
{
    /// <summary>
    /// Interaction logic for CommercialCard.xaml
    /// </summary>
    public partial class CommercialCard : Window
    {
      //  private Guid _realtorId;
        private string _cardNumber;
        private Guid _commercialCardId;
        private bool _isEdit;
        private CommercialRealEstate _currentCard;
        private Guid _newCRENewGuid;

        public CommercialCard()
        {
            InitializeComponent();

            //_realtorId = Login.UserId; /// нужно передавать в диалог
             
            var currentRealtorName = Login.UserName;
            TBxRealtor.Text = currentRealtorName;

            OpenCardViewFill();
            _isEdit = false;

        }
        public CommercialCard(Guid cardId)
        {
            InitializeComponent();

            OpenCardViewFill();

            _isEdit = true;

            _commercialCardId = cardId;
            _currentCard = AppController.ImmoRepository.GetCommercialRealEstateById(cardId);

            var currentRealtorId = _currentCard.FinancialData.FinancialDataRealtorId;

            User realtor = AppController.ImmoRepository.GetUserById(currentRealtorId);

            TBxRealtor.Text = realtor.UserFirstName +" "+ realtor.UserLastName.Substring(0,1) +". "+ realtor.UserThirdName.Substring(0,1) + ".";


            FillCommercialCard();
            _newCRENewGuid = NewCommercialCard(false);
        }

        public void OpenCardViewFill()
        {
            foreach (var region in AppController.ImmoRepository.GetAllRegions())
            {
                ComboboxRegion.Items.Add(new ComboBoxItem() { Content = region.RegionName, Tag = region.RegionId });//, Name = region.RegionId.ToString()});
            };
            ComboboxRegion.SelectedIndex = 0;

            foreach (var park in AppController.ImmoRepository.GetAllParking())
            {
                CmbBxParkingType.Items.Add(new ComboBoxItem() { Content = park.CommercialRealEstateParkingName, Tag = park.CommercialRealEstateParkingId });
            }
            CmbBxParkingType.SelectedIndex = 0;

            foreach (var typeWC in AppController.ImmoRepository.GetAllWCType())
            {
                CmbBxWC.Items.Add(new ComboBoxItem() { Content = typeWC.WCTypeName, Tag = typeWC.WCId });
            }
            CmbBxWC.SelectedIndex = 0;

            foreach (var floorType in AppController.ImmoRepository.GetAllFloorType())
            {
                CmbBxFloorMaterial.Items.Add(new ComboBoxItem() { Content = floorType.CommercialRealEstateFloorMaterialName, Tag = floorType.CommercialRealEstateFloorMaterialId });
            }
            CmbBxFloorMaterial.SelectedIndex = 0;

            foreach (var typeWall in AppController.ImmoRepository.GetAllWallsMaterial())
            {
                CmbBxWallsMaterial.Items.Add(new ComboBoxItem() { Content = typeWall.CommercialRealEstateWallsMaterialName, Tag = typeWall.CommercialRealEstateWallsMaterialId });
            }
            CmbBxWallsMaterial.SelectedIndex = 0;

            foreach (var typeEst in AppController.ImmoRepository.GetAllTypeEstate())
            {
                ComboTypeEstate.Items.Add(new ComboBoxItem() { Content = typeEst.CommercialRealEstateTypeName, Tag = typeEst.CommercialRealEstateTypeId});
            }
            ComboTypeEstate.SelectedIndex = 0;

            datePicker1.SelectedDate = DateTime.Now;
            DTPickFrom.SelectedDate = DateTime.Now;
            DTPickTo.SelectedDate = DateTime.Now;
            ShowTimeDatePic.Value = DateTime.Now;
            TBxTotalArea.Text = 0.ToString();
            TBxLineFromCentralStreet.Text = 1.ToString();
            TBxFloor.Text = 1.ToString();
            TBxFloorsCount.Text = 1.ToString();
            TBxCellHeight.Text = 3.ToString();
            TBxCost.Text = 0.ToString();

            ChBxTenant.IsChecked = false;
            DTPickFrom.Visibility = System.Windows.Visibility.Hidden;
            DTPickTo.Visibility = System.Windows.Visibility.Hidden;
            TBxTenant.Visibility = System.Windows.Visibility.Hidden;
            label26.Visibility = System.Windows.Visibility.Hidden;
            label25.Visibility = System.Windows.Visibility.Hidden;

        }

        public Guid NewCommercialCard(bool isShown)
        {
            
            Guid ownerId = AppController.ImmoRepository.AddOwner(TBxPhone.Text, TBxPhone.Text, TBxOwnerFIO.Text);

            Guid finDataId = AppController.ImmoRepository.AddFinancialData(datePicker1.SelectedDate, double.Parse(TBxCost.Text), // цена с нами!
                                                           double.Parse(TBxCost.Text),//double.Parse(TBxCostWithUs.Text),
                                                           Login.UserId, TBxContractNumber.Text, TBxSource.Text);

            int roomCount = int.Parse(((ComboBoxItem)CmbBoxRoomCount.SelectedItem).Tag.ToString());
            Guid currentFloorMaterial = (Guid)GetSelectValueComboBox(CmbBxFloorMaterial).Tag;
            Guid currentParkingType = (Guid)GetSelectValueComboBox(CmbBxParkingType).Tag;
            Guid currentWCType = (Guid)GetSelectValueComboBox(CmbBxWC).Tag;
            Guid currentRegion = (Guid)GetSelectValueComboBox(ComboboxRegion).Tag;
            Guid materialWalls = (Guid)GetSelectValueComboBox(CmbBxWallsMaterial).Tag;
            Guid typeEstate = (Guid)GetSelectValueComboBox(ComboTypeEstate).Tag;

            var commercialId = AppController.ImmoRepository.AddCommercialRealEstate(TBxAdditionalInfo.Text, TextBoxCommercialAddress.Text, ChBxIsBasemen.IsChecked, 
                finDataId, int.Parse(TBxFloor.Text),int.Parse(TBxFloorsCount.Text), currentFloorMaterial, ChBxInternet.IsChecked, double.Parse(TBxCellHeight.Text),
                TBxEntrance.Text, ChBxSeparateEntrance.IsChecked, TextBoxCommercialName.Text, ChBxTenant.IsChecked, TBxTenant.Text, int.Parse(TBxLineFromCentralStreet.Text), DTPickFrom.SelectedDate, ChckBxPhone.IsChecked, "",
                TBxCommunications.Text, ownerId, currentWCType, TBxPowers.Text, currentParkingType, TBxRepair.Text, roomCount, currentRegion, "", ShowTimeDatePic.Value,
                materialWalls, double.Parse(TBxTotalArea.Text), TBxPlacement.Text, TBxWindows.Text, DTPickTo.SelectedDate, typeEstate, PlaningTBx.Text, TBxPurpose.Text,isShown);

            if(isShown)
            {
                AppController.ImmoRepository.AddChangingStory("Добавление карты коммерческой недвижимости", commercialId,
                                         "", "", Login.UserId, "add", _cardNumber);
            }

            return commercialId;
        }

        public void EditCommercialCard()
        {
            Guid _realtorId = _currentCard.FinancialData.FinancialDataRealtorId;
            AppController.ImmoRepository.AddChangingStory("Начало редактирования карты коммерческой недвижимости",
                                               _currentCard.CommercialRealEstatetId, "", "", _realtorId, "edit", _currentCard.FinancialData.FnancialDataContract);

            int roomCount = (int)_currentCard.CommercialRealEstateRoomCount;
            Guid currentFloorMaterial = _currentCard.CommercialRealEstateFloorMaterialId;
            Guid currentParkingType = _currentCard.CommercialRealEstateParkingTypeId;
            Guid currentWCType = _currentCard.CommercialRealEstateWCId;
            Guid currentRegion = _currentCard.CommercialRealEstateRegionId;
            Guid materialWalls = _currentCard.CommercialRealEstateWallMaterialId;
            Guid typeEstate = _currentCard.CommercialRealEstateTypeId;

            DateTime finDataDate = (DateTime) _currentCard.FinancialData.FinancialDataDate;
            double finDataPrice = (double) _currentCard.FinancialData.FinancialDataPrice;
            string finDataSource = _currentCard.FinancialData.FinancialDataSource;
            string finDataContractNumber = _currentCard.FinancialData.FnancialDataContract;

            string ownerName = _currentCard.Owner.OwnerName;
            string mobile = _currentCard.Owner.OwnerMobilePhone; // для домашнего телефона поля не предусмотрено!!
           

            string additionalInfo = _currentCard.CommercialRealEstateAdditionalInformation;
            string address = _currentCard.CommercialRealEstateAddress;
            string floor = _currentCard.CommercialRealEstateFloor.ToString();
            string floorCount = _currentCard.CommercialRealEstateMaxFloors.ToString();
            string tenats = _currentCard.CommercialRealEstateTenants;
            bool hasInternet = (bool) _currentCard.CommercialRealEstateInternet;
            string cellingHeigh = _currentCard.CommercialRealEstateCellingHeigh.ToString();
            string entrance = _currentCard.CommercialRealEstateEntrance;
            bool separateEntrance = (bool) _currentCard.CommercialRealEstateEntranceSeparate;
            string objectName = _currentCard.CommercialRealEstateObject;
            string lineFromCentralStreet = _currentCard.CommercialRealEstateLineFromCentralStreet.ToString();
            bool hasPhone = (bool) _currentCard.CommercialRealEstatePhone;
            string communications = _currentCard.CommercialRealEstateCommunications;
            string powers = _currentCard.CommercialRealEstatePowers;
            string repair = _currentCard.CommercialRealEstateRepair;
            string totalArea = _currentCard.CommercialRealEstateTotalArea.ToString();
            string placement = _currentCard.CommercialRealEstatePremisesLocation;
            string windows = _currentCard.CommercialRealEstateWindows;
            bool hasTenats = (bool) _currentCard.CommercialRealEstateHasTenants;
            string planning = _currentCard.CommercialRealEstatePlanning;
            // string near = _currentCard. Ближайшие ориентиры!
            bool isBasemen = (bool) _currentCard.CommercialRealEstateBaseFloor;
            string purpose = _currentCard.CommercialRealEstateAppointment;
            var landmarks = _currentCard.CommercialRealEstateNearestLandmarks;

            #region AddHistory


            if (TextBoxNearest.Text != landmarks)
            {
                landmarks = TextBoxNearest.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Ближайшие ориентиры>", _commercialCardId,
                                                              landmarks,
                                                              _currentCard.CommercialRealEstateNearestLandmarks,
                                                              _realtorId, "edit field", _cardNumber);
            }

            if (datePicker1.SelectedDate != finDataDate)
            {
                finDataDate = (DateTime)datePicker1.SelectedDate;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Число>", _commercialCardId, finDataDate.ToString(), _currentCard.FinancialData.FinancialDataDate.ToString(), _realtorId, "edit field", _cardNumber);
            }
            if (double.Parse(TBxCost.Text) != finDataPrice )
            {
                finDataPrice = double.Parse(TBxCost.Text);
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Цена>", _commercialCardId, finDataPrice.ToString(), _currentCard.FinancialData.FinancialDataPrice.ToString(), _realtorId, "edit field", _cardNumber);
            }
            if (TBxPurpose.Text != purpose)
            {
                purpose = TBxPurpose.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Назначение объекта>", _commercialCardId, purpose, _currentCard.CommercialRealEstateAppointment, _realtorId, "edit field", _cardNumber);
            }
             if (TBxSource.Text != finDataSource)
            {
                finDataSource = TBxSource.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Источник>", _commercialCardId, finDataSource, _currentCard.FinancialData.FinancialDataSource, _realtorId, "edit field", _cardNumber);
            }
             if (TBxContractNumber.Text != finDataContractNumber)
            {
                finDataContractNumber = TBxContractNumber.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Номер договора>", _commercialCardId, finDataContractNumber, _currentCard.FinancialData.FnancialDataContract, _realtorId, "edit field", _cardNumber);
            }
            if (TBxOwnerFIO.Text != ownerName)
            {
                ownerName = TBxOwnerFIO.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <ФИО собственника>", _commercialCardId, ownerName, _currentCard.Owner.OwnerName, _realtorId, "edit field", _cardNumber);
            }
            if (TBxPhone.Text != mobile)
            {
                mobile = TBxPhone.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Телефон собственника>", _commercialCardId, mobile, _currentCard.Owner.OwnerMobilePhone, _realtorId, "edit field", _cardNumber);
            }
            if (int.Parse(((ComboBoxItem)CmbBoxRoomCount.SelectedItem).Tag.ToString()) != roomCount)
            {
                roomCount = int.Parse((string) ((ComboBoxItem) CmbBoxRoomCount.SelectedItem).Tag);
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Количество комнат>", _commercialCardId, roomCount.ToString(), _currentCard.CommercialRealEstateRoomCount.ToString(), _realtorId, "edit field", _cardNumber);
            }
 
            if ((Guid)GetSelectValueComboBox(CmbBxFloorMaterial).Tag != currentFloorMaterial)
            {
                var item = GetSelectValueComboBox(CmbBxFloorMaterial);
                currentFloorMaterial = (Guid)item.Tag;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Материал пола>", _commercialCardId, item.Content.ToString(), _currentCard.CommercialRealEstateFloorMaterial.CommercialRealEstateFloorMaterialName, _realtorId, "edit field", _cardNumber);
            }

            if ((Guid)GetSelectValueComboBox(CmbBxParkingType).Tag != currentParkingType)
            {
                var item = GetSelectValueComboBox(CmbBxParkingType);
                currentParkingType = (Guid)item.Tag;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Тип парковки>", _commercialCardId, item.Content.ToString(), _currentCard.CommercialRealEstateParking.CommercialRealEstateParkingName, _realtorId, "edit field", _cardNumber);
            }
            if ((Guid)GetSelectValueComboBox(CmbBxWC).Tag != currentWCType)
            {
                var item = GetSelectValueComboBox(CmbBxWC);
                currentWCType = (Guid)item.Tag;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Тип с/у>", _commercialCardId, item.Content.ToString(), _currentCard.WCType.WCTypeName, _realtorId, "edit field", _cardNumber);
            }
            if ((Guid)GetSelectValueComboBox(ComboboxRegion).Tag != currentRegion)
            {
                var item = GetSelectValueComboBox(ComboboxRegion);
                currentRegion = (Guid)item.Tag;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Район>", _commercialCardId, item.Content.ToString(), _currentCard.Region.RegionName, _realtorId, "edit field", _cardNumber);
            }
            if ((Guid)GetSelectValueComboBox(CmbBxWallsMaterial).Tag != materialWalls)
            {
                var item = GetSelectValueComboBox(CmbBxWallsMaterial);
                materialWalls = (Guid)item.Tag;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Материал стен>", _commercialCardId, item.Content.ToString(), _currentCard.CommercialRealEstateWallsMaterial.CommercialRealEstateWallsMaterialName, _realtorId, "edit field", _cardNumber);
            }
            if ((Guid)GetSelectValueComboBox(ComboTypeEstate).Tag != typeEstate)
            {
                var item = GetSelectValueComboBox(ComboTypeEstate);
                typeEstate = (Guid)item.Tag;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Тип коммерческой недвижимости>", _commercialCardId, item.Content.ToString(), _currentCard.CommercialRealEstateType.CommercialRealEstateTypeName, _realtorId, "edit field", _cardNumber);
            }
            if (TBxAdditionalInfo.Text != additionalInfo)
            {
                additionalInfo = TBxAdditionalInfo.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Дополнительная информация>", _commercialCardId, additionalInfo, _currentCard.CommercialRealEstateAdditionalInformation, _realtorId, "edit field", _cardNumber);
            }
            if (TextBoxCommercialAddress.Text != address)
            {
                address = TextBoxCommercialAddress.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Адрес>", _commercialCardId, address, _currentCard.CommercialRealEstateAddress, _realtorId, "edit field", _cardNumber);
            }
            if (TBxFloor.Text != floor)
            {
                floor = TBxFloor.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Этаж>", _commercialCardId, floor, _currentCard.CommercialRealEstateFloor.ToString(), _realtorId, "edit field", _cardNumber);
            }
            if (TBxFloorsCount.Text != floorCount)
            {
                floorCount = TBxFloorsCount.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Количество этажей>", _commercialCardId, floorCount, _currentCard.CommercialRealEstateMaxFloors.ToString(), _realtorId, "edit field", _cardNumber);
            }
            if (TBxTenant.Text != tenats)
            {
                tenats = TBxTenant.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Арендатор>", _commercialCardId, tenats, _currentCard.CommercialRealEstateTenants, _realtorId, "edit field", _cardNumber);
            }
            if (ChBxInternet.IsChecked != hasInternet)
            {
                hasInternet = (bool) ChBxInternet.IsChecked;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Наличие Интернета>", _commercialCardId, (hasInternet).ToString(), _currentCard.CommercialRealEstateInternet.ToString(), _realtorId, "edit field", _cardNumber);
            }
           if (TBxCellHeight.Text != cellingHeigh)
            {
                cellingHeigh = TBxCellHeight.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Высота потолка>", _commercialCardId, cellingHeigh, _currentCard.CommercialRealEstateCellingHeigh.ToString(), _realtorId, "edit field", _cardNumber);
            }
            
            if (TBxEntrance.Text!= entrance)
            {
                entrance = TBxEntrance.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Вход>", _commercialCardId, entrance, _currentCard.CommercialRealEstateEntrance, _realtorId, "edit field", _cardNumber);
            }
            if (ChBxSeparateEntrance.IsChecked!= separateEntrance)
            {
                separateEntrance = (bool)ChBxSeparateEntrance.IsChecked;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Наличие отдельного входа>", _commercialCardId, separateEntrance.ToString(), _currentCard.CommercialRealEstateEntranceSeparate.ToString(), _realtorId, "edit field", _cardNumber);
            }
            if (TextBoxCommercialName.Text != objectName)
            {
                objectName = TextBoxCommercialName.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Наименование коммерческого объекта>", _commercialCardId, objectName, _currentCard.CommercialRealEstateObject, _realtorId, "edit field", _cardNumber);
            }
            if (TBxLineFromCentralStreet.Text != lineFromCentralStreet)
            {
                lineFromCentralStreet = TBxLineFromCentralStreet.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Линия от центральной улицы>", _commercialCardId, lineFromCentralStreet, _currentCard.CommercialRealEstateLineFromCentralStreet.ToString(), _realtorId, "edit field", _cardNumber);
            }
            if (ChckBxPhone.IsChecked!= hasPhone)
            {
                hasPhone = (bool)ChckBxPhone.IsChecked;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Наличие телефона>", _commercialCardId, hasPhone.ToString(), _currentCard.CommercialRealEstatePhone.ToString(), _realtorId, "edit field", _cardNumber);
            }

            if (TBxCommunications.Text!= communications)
            {
                communications = TBxCommunications.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Коммуникации>", _commercialCardId, communications, _currentCard.CommercialRealEstateCommunications, _realtorId, "edit field", _cardNumber);
            }
            if (TBxPowers.Text != powers)
            {
                powers = TBxPowers.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Коммуникации>", _commercialCardId, powers, _currentCard.CommercialRealEstatePowers, _realtorId, "edit field", _cardNumber);
            }
            if (TBxRepair.Text != repair)
            {
                repair = TBxRepair.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Ремонт>", _commercialCardId, repair, _currentCard.CommercialRealEstateRepair, _realtorId, "edit field", _cardNumber);
            }
            if (TBxTotalArea.Text != totalArea)
            {
                totalArea = TBxTotalArea.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Общая площадь>", _commercialCardId, totalArea, _currentCard.CommercialRealEstateTotalArea.ToString(), _realtorId, "edit field", _cardNumber);
            }
            if (TBxPlacement.Text != placement)
            {
                placement = TBxPlacement.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Помещение>", _commercialCardId, placement, _currentCard.CommercialRealEstatePremisesLocation, _realtorId, "edit field", _cardNumber);
            }
            if (TBxWindows.Text != windows)
            {
                windows = TBxPlacement.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Окна>", _commercialCardId, windows, _currentCard.CommercialRealEstateWindows, _realtorId, "edit field", _cardNumber);
            }
            if (ChBxTenant.IsChecked != hasTenats)
            {
                hasTenats = (bool)ChBxTenant.IsChecked;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Наличие арендаторов>", _commercialCardId, hasTenats.ToString(), _currentCard.CommercialRealEstateHasTenants.ToString(), _realtorId, "edit field", _cardNumber);
            }
            if (PlaningTBx.Text != planning)
            {
                planning = PlaningTBx.Text;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Планировка>", _commercialCardId, planning, _currentCard.CommercialRealEstatePlanning, _realtorId, "edit field", _cardNumber);
            }
             if (ChBxIsBasemen.IsChecked!= isBasemen)
            {
                isBasemen = (bool)ChBxIsBasemen.IsChecked;
                AppController.ImmoRepository.AddChangingStory("Изменение поля <Наличие цокольного этажа>", _commercialCardId, isBasemen.ToString(), _currentCard.CommercialRealEstateBaseFloor.ToString(), _realtorId, "edit field", _cardNumber);
            }

            #endregion AddHistory




             //Owner owner = _currentCard.Owner;
             AppController.ImmoRepository.EditFinancialData(_currentCard.CommercialRealEstateFinancialDataId,
                                                               finDataDate, finDataPrice,
                                                               finDataPrice, _realtorId, finDataContractNumber, finDataSource);
            AppController.ImmoRepository.EditOwner(_currentCard.CommercialRealEstateOwnerId, "", mobile, ownerName);

            AppController.ImmoRepository.EditCommercialRealEstate(_commercialCardId, additionalInfo,
                address, isBasemen, _currentCard.CommercialRealEstateFinancialDataId, int.Parse(floor), int.Parse(floorCount), currentFloorMaterial,
                hasInternet, double.Parse(cellingHeigh), entrance, separateEntrance,
                objectName, hasTenats, tenats, int.Parse(lineFromCentralStreet), DTPickFrom.SelectedDate, hasPhone, "",
                communications, _currentCard.CommercialRealEstateOwnerId, currentWCType, powers, currentParkingType, repair, roomCount, currentRegion, "", ShowTimeDatePic.Value,
                materialWalls, double.Parse(totalArea), placement, windows, DTPickTo.SelectedDate, typeEstate, planning, purpose, _newCRENewGuid);



            AppController.ImmoRepository.AddChangingStory("Окончание редактирования карты коммерческой недвижимости",
                                   _currentCard.CommercialRealEstatetId, "", "", _realtorId, "edit", _cardNumber);

        }

        public ComboBoxItem GetSelectValueComboBox(ComboBox cmb)
        {
            return ((ComboBoxItem)cmb.SelectedItem);
        }

        public void FillCommercialCard()
        {

            TBxAdditionalInfo.Text = _currentCard.CommercialRealEstateAdditionalInformation;
            TextBoxCommercialAddress.Text = _currentCard.CommercialRealEstateAddress;
            TBxFloor.Text = _currentCard.CommercialRealEstateFloor.ToString();
            TBxTenant.Text = _currentCard.CommercialRealEstateTenants;
            ChBxInternet.IsChecked = _currentCard.CommercialRealEstateInternet;
            TBxCellHeight.Text = _currentCard.CommercialRealEstateCellingHeigh.ToString();
            TBxEntrance.Text = _currentCard.CommercialRealEstateEntrance;
            ChBxSeparateEntrance.IsChecked = _currentCard.CommercialRealEstateEntranceSeparate;
            TextBoxCommercialName.Text = _currentCard.CommercialRealEstateObject;
            TBxLineFromCentralStreet.Text = _currentCard.CommercialRealEstateLineFromCentralStreet.ToString();
            ChckBxPhone.IsChecked = _currentCard.CommercialRealEstatePhone;
            TBxCommunications.Text = _currentCard.CommercialRealEstateCommunications;
            TBxPowers.Text = _currentCard.CommercialRealEstatePowers;
            TBxRepair.Text = _currentCard.CommercialRealEstateRepair;
            TBxTotalArea.Text = _currentCard.CommercialRealEstateTotalArea.ToString();
            TBxPlacement.Text = _currentCard.CommercialRealEstatePremisesLocation;
            TBxWindows.Text = _currentCard.CommercialRealEstateWindows;
            ChBxTenant.IsChecked = _currentCard.CommercialRealEstateHasTenants;
            //TextBoxNearest.Text = _currentCard.
            PlaningTBx.Text = _currentCard.CommercialRealEstatePlanning;
            TBxOwnerFIO.Text = _currentCard.Owner.OwnerName;
            TBxPhone.Text = _currentCard.Owner.OwnerMobilePhone;
            TBxPurpose.Text = _currentCard.CommercialRealEstateAppointment;
            ShowTimeDatePic.Value = _currentCard.CommercialRealEstateShowTime;
            ChBxIsBasemen.IsChecked = _currentCard.CommercialRealEstateBaseFloor;
            TBxFloor.Value = _currentCard.CommercialRealEstateFloor;
            TBxFloorsCount.Value = _currentCard.CommercialRealEstateMaxFloors;
            TBxCellHeight.Value = _currentCard.CommercialRealEstateCellingHeigh;

            TBxContractNumber.Text = _currentCard.FinancialData.FnancialDataContract;
            TBxSource.Text = _currentCard.FinancialData.FinancialDataSource;
            TBxCost.Value = (int?) _currentCard.FinancialData.FinancialDataPrice;

            ShowTimeDatePic.Value = _currentCard.CommercialRealEstateShowTime.Value;
            datePicker1.SelectedDate = _currentCard.FinancialData.FinancialDataDate;
            DTPickFrom.SelectedDate = _currentCard.CommercialRealEstatePutPeriodFrom;
            DTPickTo.SelectedDate = _currentCard.CommercialRealEstatePutPeriodTo;


            FillComboBox(CmbBxFloorMaterial, _currentCard.CommercialRealEstateFloorMaterialId);
            FillComboBox(CmbBxParkingType, _currentCard.CommercialRealEstateParkingTypeId);
            FillComboBox(CmbBxWC, _currentCard.CommercialRealEstateWCId); 
            FillComboBox(CmbBxFloorMaterial, _currentCard.CommercialRealEstateFloorMaterialId);
            FillComboBox(ComboboxRegion, _currentCard.CommercialRealEstateRegionId);
            FillComboBox(CmbBxWallsMaterial, _currentCard.CommercialRealEstateWallMaterialId);
            FillComboBox(ComboTypeEstate, _currentCard.CommercialRealEstateTypeId);
            CmbBoxRoomCount.SelectedIndex = (int)_currentCard.CommercialRealEstateRoomCount - 1;

            TBxCardNumber.Text = _currentCard.FinancialData.FinancialDataCardNumber.ToString();

            if ((bool)ChBxTenant.IsChecked)
            {
                DTPickFrom.Visibility = System.Windows.Visibility.Visible;
                DTPickTo.Visibility = System.Windows.Visibility.Visible;
                TBxTenant.Visibility = System.Windows.Visibility.Visible;
                label26.Visibility = System.Windows.Visibility.Visible;
                label25.Visibility = System.Windows.Visibility.Visible;
            }
        }

        public void FillComboBox(ComboBox comboBox, Guid tag)
        {
            foreach (var item in comboBox.Items)
            {
                var it = item as ComboBoxItem;
                if (Guid.Parse(it.Tag.ToString()) == tag)
                {
                    comboBox.SelectedIndex = comboBox.Items.IndexOf(it);
                }
            }
        }

        private void BTnOk_Click(object sender, RoutedEventArgs e)
        {
            if(_isEdit)
            {
                EditCommercialCard();
            }
            else
                NewCommercialCard(true);
            Close();
        }

        private void BTnCancel_Click(object sender, RoutedEventArgs e)
        {
            AppController.ImmoRepository.DeleteCommercialRealEstate(_newCRENewGuid);
            Close();
        }

        private void ChBxTenant_Checked(object sender, RoutedEventArgs e)
        {
            if ((bool) ChBxTenant.IsChecked)
            {
                TBxTenant.Visibility = System.Windows.Visibility.Visible;
                DTPickFrom.Visibility = System.Windows.Visibility.Visible;
                DTPickTo.Visibility= System.Windows.Visibility.Visible;
                label26.Visibility = System.Windows.Visibility.Visible;
                label25.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                TBxTenant.Visibility = System.Windows.Visibility.Hidden;
                DTPickFrom.Visibility = System.Windows.Visibility.Hidden;
                DTPickTo.Visibility = System.Windows.Visibility.Hidden;
                label26.Visibility = System.Windows.Visibility.Hidden;
                label25.Visibility = System.Windows.Visibility.Hidden;
            }
        }

        private void ShowMapBtn_Click(object sender, RoutedEventArgs e)
        {
            var map = new Map();
            if (map.Find(((ComboBoxItem)ComboboxRegion.SelectedItem).Content + " " + TextBoxCommercialAddress.Text))
                map.ShowDialog();
            else MessageBox.Show("Не удалось определить местоположение!", "Ошибка определения местоположения");
            
        }

        private void BtnAccept_Click(object sender, RoutedEventArgs e)
        {
            AppController.ImmoRepository.AcceptCommercial(_commercialCardId, true);

            var newCRE = AppController.ImmoRepository.GetCommercialRealEstateById(_commercialCardId);

            if ((newCRE.CommercialReaEstateNewId) == null
                & ((bool)newCRE.CommercialRealEstateIsShown)) //Была добавлена
            {
                //Все уже сделано! Для различия добавленно записи и редактируемой хватает только хвостового guid, а для различия
                //с хвостовой записью нужен еще флаг IsShown
            }
            else
            {
                AppController.ImmoRepository.DeleteCommercialRealEstate(newCRE.CommercialReaEstateNewId); //Удаляем главную запись
                AppController.ImmoRepository.BreakCommerciaNewId(newCRE.CommercialRealEstatetId);
                AppController.ImmoRepository.SetShownCommercial(newCRE.CommercialRealEstatetId, true); //Делаем дочернюю запись главной
            }
            AppController.ImmoRepository.DeleteCommercialRealEstate(_newCRENewGuid);

            Close();
        }

        private void BtnReject_Click(object sender, RoutedEventArgs e)
        {
            AppController.ImmoRepository.AcceptCommercial(_commercialCardId, false);
            var addedCommercial = AppController.ImmoRepository.GetCommercialRealEstateById(_commercialCardId);

            if (addedCommercial.CommercialReaEstateNewId == null) //Была добавлена
            {
                AppController.ImmoRepository.DeleteCommercialRealEstate(_commercialCardId);
            }
            else
            {
                AppController.ImmoRepository.DeleteCommercialRealEstate(addedCommercial.CommercialRealEstatetId);
                AppController.ImmoRepository.BreakCommerciaNewId(addedCommercial.CommercialReaEstateNewId);
                AppController.ImmoRepository.SetShownCommercial(addedCommercial.CommercialReaEstateNewId, true);
            }

            AppController.ImmoRepository.DeleteCommercialRealEstate(_newCRENewGuid);
            Close();
        }
    }
}
